<?php
/**
 * $Id$
 */
class MaxIDCtrlClass
{
	private $_dbName = 'master_db';
	private $_serverID = 5;
	private $_lockTimeout = 5;
	private $_lockRetry = 15;
	private $_key = '---';
	private $_isLock = false;
	private $_type = '';
	
	public function __construct($idType = '')
	{
		$this->setType($idType);
	}
	
	public function setType($idType)
	{
		$this->_type = $idType;
	}
	
	public function _setLockTimeout($timeout)
	{
		$timeout = intval($timeout);
		$this->_lockTimeout = $timeout;
		return $timeout;
	}
	
	public function _getMaxID()
	{
		$sql = "SELECT maxID FROM {$this->_dbName}.IDCtrlTbl WHERE _type='{$this->_type}' OR _key='{$this->_key}' LIMIT 0,1";
		$rs = db_query_sql($sql, $this->_serverID, false);
		return $rs[0]['maxID'];
	}
	
	public function _setMaxID($maxID)
	{
		if(empty($maxID) || intval($maxID) != $maxID)
		{
			return false;
		}
		$sql = "UPDATE {$this->_dbName}.IDCtrlTbl SET maxID='{$maxID}', lockTime=0 WHERE _key='{$this->_key}'";
		db_query_sql($sql, $this->_serverID);
		return (bool)db_get_affected_rows();
	}
	
	public function _lock()
	{
		$this->_key = createRandString(32, '____lock_maxid');
		
		$sql = "UPDATE {$this->_dbName}.IDCtrlTbl SET _lock='y', _key='{$this->_key}', lockTime=".(G_CURR_TIMESTAMP + $this->_lockTimeout)." WHERE _type='{$this->_type}' AND lockTime<".G_CURR_TIMESTAMP;
		for($i = 1; $i <= $this->_lockRetry; $i ++)
		{
			db_query_sql($sql, $this->_serverID);
			if(db_get_affected_rows())
			{
				$this->_isLock = true;
				return true;
			}
			usleep(100);
		}
		$this->_key = 'xxx';
		return false;
	}
	
	public function _unlock()
	{
		$sql = "UPDATE {$this->_dbName}.IDCtrlTbl SET _lock='n', lockTime=0 WHERE _key='{$this->_key}'";
		db_query_sql($sql, $this->_serverID);
		return (bool)db_get_affected_rows();
	}
}

